var DATABASE_NAME = 'Expense';

exports.createDb = function() {
	Ti.Database.install('Expense.sqlite', DATABASE_NAME);
};

exports.selectItems = function() {
	var retData = [];
	var db = Ti.Database.open(DATABASE_NAME);
	var rows = db.execute('select * from Expenses');
	while (rows.isValidRow()) {
		retData.push({ Id:rows.fieldByName('Id'), Name:rows.fieldByName('Name'), Price:rows.fieldByName('Price'), Date:rows.fieldByName('Date')});
		rows.next();
	}
	db.close();
	return retData;
};

exports.selectItem = function(_id) {
	//var retData = null;
	var retData={ };
//	var retData = [];
	var db = Ti.Database.open(DATABASE_NAME);
	var rows = db.execute('select * from Expenses where Id=?',_id);
	if (rows.isValidRow()) {
		retData = { Id:rows.fieldByName('Id'), Name:rows.fieldByName('Name'), Price:rows.fieldByName('Price'), Date:rows.fieldByName('Date')};		
		//retData = { Id:rows.fieldByName('Id'), Name:rows.fieldByName('Name'), Price:rows.fieldByName('Price'), Date:rows.fieldByName('Date')};				
		//retData.push({ Id:rows.fieldByName('Id'), Name:rows.fieldByName('Name'), Price:rows.fieldByName('Price'), Date:rows.fieldByName('Date')});
			
	}
	db.close();
	return retData;
};

exports.updateItem = function(_id, _name, _price, _date) { 
	var mydb = Ti.Database.open(DATABASE_NAME);
	mydb.execute('update Expenses set Name = ?, Price = ?, Date = ? where Id = ?', _name, _price, _date, _id);
	var rows = mydb.execute('select * from Expenses');
	mydb.close();
	return rows;
};

exports.addItem = function(_name,_price,_date) {
	var mydb = Ti.Database.open(DATABASE_NAME);
	mydb.execute('insert into Expenses (Name,Price,Date) values (?,?,?)', _name, _price, _date);
	mydb.close();
};

exports.deleteItem = function(_id) {
	var mydb = Ti.Database.open(DATABASE_NAME);
	mydb.execute('delete from Expenses where Id = ?', _id);
	mydb.close();
};
